import tcpserial
from tcpserial import TcpCmdClient

# ------------------------------------------------------
# Remote client
# ------------------------------------------------------


class RemoteClient:
    def __init__(self, cmd_handler):
        self.cmd_handler = cmd_handler

    # 'private' methods
    def _parseResponse(self,response):
        ret = {}
        parts = response.split(' ')
        lastkey = None

        for part in parts:
            expr = part.split(':')

            # keep only last expr (e.g. from 'SMT:A:0' keep 'A:0')
            if len(expr) > 2:
                expr = expr[len(expr)-2:]
            # assign to previous key
            elif len(expr) < 2:
                if lastkey != None:
                    ret[lastkey] += " " + part
                continue    # ignore

            # set in dict
            ret[expr[0]] = expr[1]
            lastkey = expr[0]

        # done
        return ret

    def _command(self,command,**args):
        response = self.cmd_handler.command(command)
        if response == None:
            return args

        initial = args
        response = self._parseResponse(response)
        initial.update(response)
        return initial

    def getTemp(self):
        return float(self._command("adc temp",T=None)["T"])

    def getLight(self):
        return int(self._command("adc light",L=None)["L"])

    def getLightInMV(self):
        return int(self._command("adc light",MV=None)["MV"])

    def getConfig(self,selector):
        selector = selector + "="
        return int(self._command(selector,V=None)["V"],16)






